import 'package:dali_ng_pera/page/widget/dnp_app_bar.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:ios_keyboard_action/ios_keyboard_action.dart';

import 'dnp_calculator_controller.dart';
import 'dnp_calculator_model.dart';

class DnpCalculatorPage extends StatefulWidget {
  const DnpCalculatorPage({super.key});

  @override
  State<DnpCalculatorPage> createState() => _DnpCalculatorPageState();
}

class _DnpCalculatorPageState extends State<DnpCalculatorPage> {
  final controller = Get.put(DnpCalculatorController());
  final amountTextController = TextEditingController();
  final interestTextController = TextEditingController();
  final loanTermTextController = TextEditingController();

  FocusNode amountFocusNode = FocusNode();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [
              Color(0xFF53A9FF),
              Color(0xFFDFF1FF),
            ],
          ),
        ),
        child: Column(
          children: [
            DnpAppBar(title: "Calculator"),
            Expanded(
              child: Obx(() => ListView.builder(
                  padding:
                      EdgeInsets.only(top: 9, left: 14, right: 14, bottom: 14),
                  itemCount: (controller.zest.length).clamp(1, 99999999),
                  itemBuilder: (context, index) {
                    return Column(
                      children: [
                        if (index == 0) ...[
                          _buildHeader(),
                          if (controller.zest.isNotEmpty) ...[
                            _buildHeaderSecond(),
                          ],
                          SizedBox(
                            height: 9,
                          ),
                        ],
                        if (controller.zest.isNotEmpty) ...[
                          _buildItem(controller.zest[index])
                        ],
                        if (controller.zest.isEmpty) ...[_buildEmpty()],
                      ],
                    );
                  })),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildHeader() {
    return Container(
      width: double.infinity,
      height: 398,
      child: Column(
        children: [
          Image.asset(
            "assets/images/ic_calculator_bg.webp",
            width: double.infinity,
            height: 130,
            fit: BoxFit.fill,
          ),
          Expanded(
            child: Container(
              width: double.infinity,
              padding: EdgeInsets.only(left: 14, right: 14),
              decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.only(
                      bottomLeft: Radius.circular(20),
                      bottomRight: Radius.circular(20)),
                  border: Border(
                    left: BorderSide(color: Color(0xFF1D4AC8), width: 1.0),
                    right: BorderSide(color: Color(0xFF1D4AC8), width: 1.0),
                    bottom: BorderSide(color: Color(0xFF1D4AC8), width: 1.0),
                  )),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    "Loan amount",
                    style: TextStyle(
                        fontWeight: FontWeight.w500,
                        fontSize: 14,
                        color: Color(0xFF252630)),
                  ),
                  SizedBox(
                    height: 10,
                  ),
                  _buildTextField(FocusNode(),"Please enter the loan amount", "₱",
                      amountTextController, allowDecimal: false),
                  SizedBox(
                    height: 12,
                  ),
                  Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Expanded(
                          child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            "Interest",
                            style: TextStyle(
                                fontWeight: FontWeight.w500,
                                fontSize: 14,
                                color: Color(0xFF252630)),
                          ),
                          SizedBox(
                            height: 10,
                          ),
                          _buildTextField(FocusNode(),
                              "Please enter", "%", interestTextController),
                        ],
                      )),
                      SizedBox(
                        width: 12,
                      ),
                      Expanded(
                          child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            "Loan term",
                            style: TextStyle(
                                fontWeight: FontWeight.w500,
                                fontSize: 14,
                                color: Color(0xFF252630)),
                          ),
                          SizedBox(
                            height: 10,
                          ),
                          _buildTextField(FocusNode(),
                              "Please enter", "days", loanTermTextController, allowDecimal: false),
                        ],
                      ))
                    ],
                  ),
                  SizedBox(
                    height: 15,
                  ),
                  GestureDetector(
                    onTap: () {
                      amountTextController.text = "";
                      interestTextController.text = "";
                      loanTermTextController.text = "";
                      controller.calculatorModel.value = DnpCalculatorModel();
                    },
                    child: Center(
                      child: Image.asset(
                        "assets/images/ic_calculator_reset_icon.png",
                        width: 53,
                        height: 17,
                      ),
                    ),
                  ),
                  SizedBox(
                    height: 10,
                  ),
                  GestureDetector(
                    behavior: HitTestBehavior.translucent,
                    onTap: () {
                      var comfort = amountTextController.text;
                      var unrobed = interestTextController.text;
                      var sure = loanTermTextController.text;
                      int? comfortInt = int.tryParse(comfort);
                      int? sureInt = int.tryParse(sure);
                      double? unrobedDouble = double.tryParse(unrobed);
                      controller.onRequestCalculator(
                          comfortInt, unrobedDouble, sureInt);
                    },
                    child: Container(
                      width: double.infinity,
                      height: 48,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(16),
                        color: Color(0xFF1D4AC8),
                      ),
                      child: Center(
                        child: Text(
                          "Calculate",
                          style: TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.w600,
                              color: Colors.white),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildHeaderSecond() {
    return Container(
      margin: EdgeInsets.only(top: 16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            "Calculation results",
            style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w500,
                color: Color(0xFF252630)),
          ),
          SizedBox(
            height: 14,
          ),
          Row(
            children: [
              Obx(() => _buildHeaderSecondTextItem("interest payable",
                  controller.calculatorModel.value.gibbon ?? "")),
              Container(
                width: 1,
                height: 38,
                color: Color(0xFFB9C8D4),
              ),
              Obx(() => _buildHeaderSecondTextItem("Principal amount",
                  controller.calculatorModel.value.comfort ?? "")),
              Container(
                width: 1,
                height: 38,
                color: Color(0xFFB9C8D4),
              ),
              Obx(() => _buildHeaderSecondTextItem("Full payment",
                  controller.calculatorModel.value.unpacking ?? "")),
            ],
          )
        ],
      ),
    );
  }

  Widget _buildHeaderSecondTextItem(String title, String value) {
    return Expanded(
        child: Column(
      children: [
        Text(
          value,
          style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.w500,
              color: Color(0xFF1D4AC8)),
        ),
        SizedBox(
          height: 6,
        ),
        Text(title,
            style: TextStyle(
              fontSize: 14,
              fontWeight: FontWeight.w400,
              color: Color(0xFF252630),
            ))
      ],
    ));
  }

  Widget _buildTextField(FocusNode focusNode,
      String hint, String tag, TextEditingController textEditingController,
      {bool allowDecimal = true}) {
    return Container(
      width: double.infinity,
      height: 49,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(16),
        color: Color(0xFFE9F5FF),
      ),
      child: Row(
        children: [
          Expanded(
            child: IOSKeyboardAction(
              focusNode: focusNode,
              backgroundColor:Colors.grey.shade300,
              label: "Done",
              textColor: Colors.blue,
              focusActionType: FocusActionType.done,
              onTap: (){
                FocusScope.of(context).requestFocus(FocusNode());
              },
              child: TextField(
                focusNode: focusNode,
                controller: textEditingController,
                keyboardType: TextInputType.numberWithOptions(decimal: allowDecimal),
                inputFormatters: [
                  FilteringTextInputFormatter.allow(
                    allowDecimal ? RegExp(r'^\d*\.?\d*') : RegExp(r'^\d*')
                  ),
                ],
                style: TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.w400,
                  color: Color(0xFF252630),
                ),
                decoration: InputDecoration(
                  filled: true,
                  fillColor: Colors.transparent,
                  hintText: hint,
                  hintStyle: TextStyle(
                    fontSize: 14,
                    fontWeight: FontWeight.w400,
                    color: Color(0xFFABABAB),
                  ),
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(16),
                    borderSide: BorderSide(
                      color: Colors.transparent,
                      width: 1,
                    ),
                  ),
                  enabledBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(16),
                    borderSide: BorderSide(
                      color: Colors.transparent,
                      width: 1,
                    ),
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(16),
                    borderSide: BorderSide(
                      color: Colors.transparent,
                      width: 2,
                    ),
                  ),
                ),
              ),
            ),
          ),
          SizedBox(
            width: 11,
          ),
          Text(
            tag,
            style: TextStyle(
                color: Color(0xFF1D4AC8),
                fontSize: 14,
                fontWeight: FontWeight.w400),
          ),
          SizedBox(
            width: 14,
          ),
        ],
      ),
    );
  }

  Widget _buildItem(DnpCalculatorRepaymentItemModel zest) {
    return Container(
      margin: EdgeInsets.only(top: 7, bottom: 7),
      padding: EdgeInsets.only(left: 10, right: 10, top: 14, bottom: 14),
      width: double.infinity,
      height: 132,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(14),
        color: Colors.white,
      ),
      child: Column(
        children: [
          Row(
            children: [
              Text(
                "Loan amount",
                style: TextStyle(
                    fontSize: 15,
                    fontWeight: FontWeight.w400,
                    color: Color(0xFF252630)),
              ),
              SizedBox(
                width: 6,
              ),
              Text(
                zest.merest ?? "",
                style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w500,
                    color: Color(0xFF1D4AC8)),
              ),
            ],
          ),
          SizedBox(
            height: 8,
          ),
          Container(
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(10),
              color: Color(0xFFE9F5FF),
            ),
            padding: EdgeInsets.only(left: 12, right: 12, top: 12, bottom: 12),
            child: Column(
              children: [
                Row(children: [
                  Text(
                    "Payment time",
                    style: TextStyle(
                        fontSize: 15,
                        fontWeight: FontWeight.w400,
                        color: Color(0xFF848484)),
                  ),
                  Spacer(),
                  Text(zest.fancy ?? "",
                      style: TextStyle(
                          fontSize: 15,
                          fontWeight: FontWeight.w400,
                          color: Color(0xFF252630)))
                ]),
                SizedBox(
                  height: 12,
                ),
                Row(children: [
                  Text(
                    "Payment progress",
                    style: TextStyle(
                        fontSize: 15,
                        fontWeight: FontWeight.w400,
                        color: Color(0xFF848484)),
                  ),
                  Spacer(),
                  Text("${zest.passing}/${controller.zest.length}",
                      style: TextStyle(
                          fontSize: 15,
                          fontWeight: FontWeight.w400,
                          color: Color(0xFF252630)))
                ])
              ],
            ),
          )
        ],
      ),
    );
  }

  Widget _buildEmpty() {
    return Container(
      margin: EdgeInsets.only(top: 50, bottom: 50),
      child: Image.asset(
        "assets/images/ic_calculator_empty_bg.webp",
        width: 236,
        height: 185,
        fit: BoxFit.cover,
      ),
    );
  }
}
